﻿using Kinlo.Entitys;
using Kinlo.MESDocking;
using LiveChartsCore.Measure;
using NPOI.OpenXmlFormats.Spreadsheet;
using Org.BouncyCastle.Ocsp;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using UIWindows.GlobalStatics;
using UIWindows.MESModels;
using UIWindows.Models.Devices;
using UIWindows.Tools.Helper;
using XingLucifer.Devices;
using XingLucifer.IBase.Enums;
using static NPOI.HSSF.Util.HSSFColor;

namespace UIWindows.Services.PLC_MESHelper
{
    /// <summary>
    /// 预充下料托盘扫码
    /// </summary>
    public class BlankingScanBarcodeHandler : HelperBase
    {
        PLCBase InjMachine { get; set; }

        PrechargeTrayInfo _prechargeTrayInfo { get; set; }
        public BlankingScanBarcodeHandler(
            DeviceInteractiveaddressStatic deviceInteractiveaddressStatic,
            DeviceClientModel deviceModel,
            TemporaryStatic temporaryStatic,
            ParameterStatic parameterStatic,
            DeviceConfigStatic deviceConfigStatic,
            SystemConfigStatic systemConfigStatic,
             HomeStatic homeStatic,
             Action<string, string, string, string, string, long, DateTime, string, string, string, string> log, Action<string, string, string> dialog
            ) : base(deviceInteractiveaddressStatic, deviceModel, temporaryStatic, parameterStatic, deviceConfigStatic, systemConfigStatic, homeStatic, log, dialog)
        {
            InjMachine = deviceModel.PLC;
            _prechargeTrayInfo = new PrechargeTrayInfo(_log, _dialog);
        }

        public override Task Handle()
        {
            //KL21050011Machine InjMachine = null;
            Int16 testResult = 2;
            Int16 battId = 0;
            //List<KNCScannerMachine> Scanner = null;
            var barcode = "";
            ushort trayNo = 0;
            //创建一个包含256个元素的数组，每个元素初始值值都是3,用于存储每个电池的状态信息
            var results = Enumerable.Repeat<short>(3, 256).ToArray();
            try
            {
                //var dicts = ctx.Container.Get<ConcurrentDictionary<string, object>>();
                //var cfg = ctx.Container.Get<CFG>();
                //var mescfg = ctx.Container.Get<MesCFG>();
                RunLog($"【下料托盘扫码开始】");

                //InjMachine = (KL21050011Machine)dicts.GetOrAdd("InjMachine", InjMachine);

                DeviceClientModel? device = _deviceConfig.DeviceList.FirstOrDefault(x => x.ServiceName == _deviceModel.ServiceName
            && x.TaskType == TaskTypes.预充下料托盘扫码);

                if (device == null)
                {
                    RunLog($"-预充下料托盘扫码 触发设备位置找不到，请注意!!!", MessageLevelType.错误);
                    return Task.CompletedTask;
                }

                barcode = ScanCode(_parameterStatic.RunParameter.Retries_Count_ScanCode, device.Communication, 1);

                if (string.IsNullOrWhiteSpace(barcode))
                {
                    testResult = 2;
                    RunLog($"【预充下料托盘扫码码】扫码失败");
                }
                else
                {

                    //OCV.Meta.TableName = $"OCV_{StartTime:yyyy}{StartTime.GetQuarterly()}";

                    OCV.Meta.TableName = $"OCV_{startTime:yyyy}{startTime.GetQuarterly()}";
                    Precharge.Meta.TableName = $"Precharge_{startTime:yyyy}{startTime.GetQuarterly()}";
                    Plate.Meta.TableName = $"Plate_{startTime:yyyy}{startTime.GetQuarterly()}";


                    RunLog($"【下料托盘扫码】 {barcode} ");

                    //todo 从MES取结果
                    testResult = 1;

                    //if (_parameterStatic.DecideParameter.EnableMES)
                    //{
                        var trayId1Data = OCV.FindAll(OCV._.TrayCode == barcode);
                        

                        var trayId2Data = Precharge.FindAll(Precharge._.TrayCode == barcode);
                       

                        var trayId3Data = Plate.FindAll(Plate._.TrayBarcode == barcode);
                       
                        if(trayId1Data==null|| trayId1Data.Count==0||
                            trayId2Data == null || trayId2Data.Count == 0||
                            trayId3Data == null || trayId3Data.Count == 0)
                        {
                            RunLog($"【下料托盘扫码】 {barcode}数据查询失败！！！");
                            return Task.CompletedTask;
                        }

                        var trayId2 = trayId2Data.Max(p => p.TrayID);

                        var trayId1 = trayId1Data.Max(p => p.TrayID);

                        var trayId3 = trayId3Data.Max(p => p.TrayID);

                        if (trayId1 == 0 || trayId2 == 0 || trayId3 == 0)
                        {
                            RunLog($"【下料托盘扫码】 {barcode}数据查询失败{trayId1},{trayId2} ");
                            return Task.CompletedTask;
                        }
                        // 查询OCV和Precharge数据
                        var batts1Task = OCV.FindAll(OCV._.TrayID == trayId1);
                        var batts2Task = Precharge.FindAll(Precharge._.TrayID == trayId2);
                        var batts3Task = Plate.FindAll(Plate._.TrayID == trayId3);

                        //await Task.WhenAll(batts1Task, batts2Task);

                        var batts1 = batts1Task.ToList();
                        var batts2 = batts2Task.ToList();
                        var batts3 = batts3Task.OrderBy(x => x.ProductDate).ToList();

                        // 构造MESPrechargeTrayInfoModel对象
                        MESPrechargeTrayInfoModel tmpdata = new MESPrechargeTrayInfoModel();
                        tmpdata.parentvo = new MESPrechargeTrayInfoModelParentvo();
                        tmpdata.parentvo.TrayNomber = barcode;
                        tmpdata.parentvo.Dishupstarttime = batts3.First().ProductDate.ToString(); //装盘开始时间取第一个电池装盘时间
                        tmpdata.parentvo.Dishupfinishtime = batts3.Last().ProductDate.ToString();//装盘结束时间取最后一个电池装盘时间
                                                                                                 //tmpdata.parentvo.Dishupfinishtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                                                                                 //tmpdata.parentvo.Amount = results.Count().ToString();

                        //tmpdata.parentvo.Amount = batts1.Where(x => x.BatteryStatus == 1).ToList().Count().ToString();

                        tmpdata.parentvo.Workorder = _parameter.WorkOrder;
                        tmpdata.parentvo.Partnumber = _parameter.Material_Code;
                        tmpdata.parentvo.ProductMark = _parameter.ProductMark;
                        //tmpdata.parentvo.Modelnumber = cfg.Material_Spec;
                        tmpdata.parentvo.Modelnumber = _parameter.Material_Spec;
                        tmpdata.parentvo.Equipment = _parameter.EquipmentCode;
                        tmpdata.parentvo.Operator = _parameter.UserName;
                        tmpdata.parentvo.Batchnumber = _parameter.BatchNo;
                        tmpdata.parentvo.Into_State = "0";
                        tmpdata.childrenvo = new List<MESPrechargeTrayInfoModelChildrenvo>();

                        int OKCount = 0;
                        int OCVNGCount= 0;
                        int PrechargeNGCount = 0;

                        string OCVNGPosition = "";
                        string PrechargeNGPosition = "";
                        string nullPosition = "";
                        // 处理每个电池的数据
                        for (int i = 0; i < results.Count(); i++)
                        {
                            //取出OCV和预充机相同的位置电池数据
                            var b1 = batts1.Where(x => x.Position == i + 1).FirstOrDefault();
                            var b2 = batts2.Where(x => x.Position == i + 1).FirstOrDefault();
                            if (b1 != null && b2 != null)
                            {
                                // 判断电池状态
                                if (b1.BatteryStatus == b2.BatteryStatus && b1.BatteryStatus == 1)
                                {
                                    results[i] = 1;
                                    OKCount += 1;
                                    _parameter.OKCount += 1;
                                }
                                else if (b1.BatteryStatus == 2)
                                {
                                    results[i] = 2;
                                    OCVNGCount += 1;
                                    _parameter.NGCount += 1;
                                    OCVNGPosition += b1.Position + "、";
                                }
                                else if (b2.BatteryStatus == 2|| b2.BatteryStatus == 3)
                                {
                                    results[i] = 4;
                                    PrechargeNGCount += 1;
                                    _parameter.NGCount += 1;
                                    PrechargeNGPosition += b2.Position + "、";
                                }
                                else
                                {
                                    results[i] = 3;
                                    nullPosition += b2.Position + "、";
                                }
                                   

                                _temporaryStatic.mesCollectionItemsTemporary[(int)machineInfo_Type].OKCount = _parameter.OKCount;
                                _temporaryStatic.mesCollectionItemsTemporary[(int)machineInfo_Type].NGCount = _parameter.NGCount;

                                // 检查电池条码是否为空
                                if (b1.BatteryCode == "" && b2.BatteryCode == "")
                                {
                                    results[i] = 3;
                                }
                            }
                            else
                            {
                                if (b1?.BatteryStatus == 2 || b2?.BatteryStatus == 2)
                                    results[i] = 2;
                                else
                                    results[i] = 3;
                            }

                            //tmpdata.parentvo.Process = b2.ProcessNO;
                            tmpdata.parentvo.Process = _parameter.process_id;
                            MESPrechargeTrayInfoModelChildrenvo tmp = new MESPrechargeTrayInfoModelChildrenvo();
                            tmp.TrayNomber = barcode;
                            //tmp.Batteries = b1.BatteryCode;
                            tmp.Batteries = b1.BatteryCode == null ? "0" : b1.BatteryCode;
                            tmp.Location = b1.Position.ToString();
                            tmp.Grade = results[i] == 1 ? "OK" : "NG";
                            if ((b1.BatteryStatus == 0 || b2.BatteryStatus == 0))
                            {
                                tmp.Ngcode = "0";
                            }
                            else if (b1.BatteryStatus != 1 || b2.BatteryStatus != 1)
                            {
                                tmp.Ngcode = "2";
                            }
                            else
                            {
                                tmp.Ngcode = "1";
                            }
                            string irValue = "0";
                            string voltageValue = "0";
                            if (!string.IsNullOrWhiteSpace(b1.IR) && b1.IR != null)
                            {
                                irValue = b1.IR;
                            }
                            if (!string.IsNullOrWhiteSpace(b1.Voltage) && b1.Voltage != null)
                            {
                                voltageValue = b1.Voltage;
                            }

                            switch (b1.BatteryStatus)
                            {
                                default:
                                case 0: tmp.Ocv = "NULL"; break;
                                case 1: tmp.Ocv = "OK"; break;
                                case 2: tmp.Ocv = "NG"; break;
                            }

                        //tmp.Ocv = "NULL";
                            tmp.Ir = irValue;
                            tmp.Voltage = voltageValue;
                            tmp.YuChong_Parameters3 = barcode;
                            tmp.YuChong_Parameters4 = irValue;
                            tmp.YuChong_Parameters5 = voltageValue;
                            tmp.YuChong_Parameters6 = _parameter.Steptype;
                            tmp.YuChong_Parameters7 = _parameter.StepNumber;
                            tmp.YuChong_Parameters8 = b2.Current == null ? "0" : b2.Current;
                            tmp.YuChong_Parameters9 = b2.Capacity == null ? "0" : b2.Capacity;
                            tmp.YuChong_Parameters10 = b2.Energy == null ? "0" : b2.Energy;
                            tmp.Voltage1 = voltageValue;
                            tmpdata.childrenvo.Add(tmp);


                            // results[i] = (short)((b1 != null && b2 != null) ? (b1.BatteryStatus == b2.BatteryStatus && b1.BatteryStatus == 1) ? 1 : 2 : 2);
                        }

                        tmpdata.parentvo.Amount = OKCount.ToString();
                        RunLog($"托盘号{barcode}，总OK数量：{OKCount.ToString()}，OCVNG数量：{OCVNGCount.ToString()}，预充NG数量：{PrechargeNGCount.ToString()}");
                        RunLog($"托盘号{barcode}，OCVNG电池位置：{OCVNGPosition}，预充NG数量：{PrechargeNGPosition}，空盘电池位置：{nullPosition}");

                        if (_parameterStatic.DecideParameter.EnableMES)
                        {
                            Dictionary<string, object> mesParam = new Dictionary<string, object>
                            {
                                { "EquipmentCode", _parameter.EquipmentCode==null?"": _parameter.EquipmentCode },
                                { "process_id", _parameter.process_id==null?"": _parameter.process_id },
                                { "parameter",tmpdata },
                            };

                            var result = _prechargeTrayInfo.MESInteraction(_parameterStatic.MESParameter.OeeCapacityRouter,
                         _parameterStatic.MESParameter.OeeCapacityTime,
                         1, DateTime.Now, mesParam);

                        }
                    }
                      
                //}

            }
            catch (Exception ex)
            {
                testResult = 2;
                RunLog($"【下料托盘扫码】发生异常:{ex}");
            }
            finally
            {
                var r1 = InjMachine.Write<short>("DM28000", results);
                var r2 = InjMachine.Write<short>("DM1212", new short[] { testResult });
                var r3 = InjMachine.Write<short>("DM1211", new short[] { 1 });      //完成扫描信号写入
                var r4 = InjMachine.Write<short>("DM1010", new short[] { 0 });       //PLC握手
                RunLog( $"【下料托盘扫码】写结果信号 {testResult} {r1}.{r2}.{r3}.{r4} {string.Join(",", results)} {(r1 && r1 && r3 && r4 ? "成功" : "失败")}");
            }

            return base.Handle();
        }
    }
}
